<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Download extends Model
{
    use HasFactory;

    protected $guarded = [''];

    public function downloadByCoverId($user_id, $cover_id, $index)
    {
        try{
            $cover = Cover::query()->find($cover_id);
            if (!$cover)  throw new \Exception('作品不存在');
            if ($cover->status != 1) throw new \Exception('作品已下架');

            $cover_img = $cover->images[$index];
            // 查看是否曾经下载过
            $is_old_download = $this->query()
                ->where('image', $cover_img)
                ->where('user_id', $user_id)
                ->exists();
            // 有下载记录  不再扣除积分
            if ($is_old_download)  return true;

            // 查询用户信息
            $user = User::query()->where('state',1)->where('id',$user_id)->first();
            if (!$user) throw new \Exception('用户不存在');

            // 查询作者信息
            $author = User::query()->where('state',1)->where('id',$cover->user_id)->first();
            if (!$author) throw new \Exception('作者不存在');

            DB::beginTransaction();

            // 查询下载扣除积分情况
            $config = Config::query()->where('key','downIntegral')->first();
            if (!$config) throw new \Exception('未配置下载扣除积分');
            $integral = intval($config->val);

            if ($integral > 0) {
                // 判断积分
                if ($user->integral < $integral) throw new \Exception('积分不足');

                // 作者增加积分
                $author->incIntegral($integral);

                // 添加积分记录
                Record::query()->create([
                    'mode' => 0,
                    'name' => $user->nickname . ' 下载您的壁纸：' . $cover->name,
                    'integral' => $integral,
                    'user_id' => $author->id
                ]);

                // 用户扣除积分
                $user->decIntegral($integral);

                // 添加积分记录
                Record::query()->create([
                    'mode' => 0,
                    'name' => '下载壁纸：' . $cover->name,
                    'integral' => $integral,
                    'user_id' => $user->id
                ]);
            }

            // 创建下载记录
            $this->query()->create([
                'user_id' => $user->id,
                'author_id' => $author->id,
                'cover_id' => $cover_id,
                'integral' => $integral,
                'current' => $index,
                'image' => $cover_img,
                'state' => 1
            ]);

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            Log::channel('daily')->error('Line:' . $exception->getLine(). ' Message:'.$exception->getMessage());
            return false;
        }


    }
}
